<template>
  <!-- 添加问题 -->
  <div style="font-size: 14px">
    <el-drawer v-model="dialogVisible" title="请求升级成问题" direction="rtl" size="1000">
      <div v-loading="loading">
        <el-form ref="addForm" v-if="dialogVisible" :model="form" :rules="rules" label-width="120">
          <el-form-item label="问题标题" prop="etitle">
            <el-input v-model="form.etitle" placeholder="请输入问题标题" />
          </el-form-item>
          <el-form-item label="问题描述" required>
            <WangEditor v-model:value="form.edesc" height="200px" />
          </el-form-item>
          <el-row>
            <el-col :span="12">
              <el-form-item label="所属客户" prop="companyNo">
                <el-select v-model="form.companyNo" :disabled="details.eno" placeholder="请选择所属客户">
                  <el-option v-for="item in orgList" :key="item.orgNo" :label="item.orgName" :value="item.orgNo" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="问题分类" prop="categoryName">
                <el-select v-model="form.categoryNo" placeholder="请选择问题分类">
                  <el-option v-for="item in cateList" :key="item.cname" :label="item.cname" :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="期望完成日期">
                <el-date-picker
                  v-model="form.overdueTime"
                  type="datetime"
                  value-format="YYYY-MM-DD hh:mm:ss"
                  placeholder="请选择"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="优先级">
                <el-select v-model="form.priorityNo" placeholder="请选择优先级">
                  <el-option v-for="item in priorityList" :key="item.dcode" :label="item.dname" :value="item.dcode" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="影响范围">
                <el-select v-model="form.effectRangeNo" placeholder="请选择影响范围">
                  <el-option v-for="item in effectRangeList" :key="item.dcode" :label="item.dname" :value="item.dcode" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="紧急度">
                <el-select v-model="form.seriousnessNo" placeholder="请选择紧急度">
                  <el-option v-for="item in seriousnessList" :key="item.dcode" :label="item.dname" :value="item.dcode" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-tabs v-model="tabName" class="demo-tabs">
                <el-tab-pane label="拓展信息" name="one">
                  <div v-for="(item, index) in attrVals" :key="index">
                    <div style="margin-bottom: 8px; font-weight: bold">{{ item.attrGroupName }}</div>
                    <div class="table-data-box">
                      <div class="data-cell row" v-for="(vo, idx) in item.children" :key="idx">
                        <div class="label w-200">{{ vo.attrAsName }}</div>
                        <div class="content">
                          <!-- 文本 -->
                          <el-input v-if="vo.attrType == 'String'" v-model="vo.value" />
                          <!-- 时间 -->
                          <el-date-picker
                            v-if="vo.attrType == 'Date'"
                            v-model="vo.value"
                            type="datetime"
                            placeholder="请选择时间"
                            value-format="YYYY-MM-DD HH:mm:ss"
                            style="width: 100%"
                          />
                          <template v-if="vo.attrType == 'DataDictionaray'">
                            <!-- 选择优先级 -->
                            <el-select v-if="vo.attrdataDictionary == 'priority'" v-model="vo.value" placeholder="请选择优先级">
                              <el-option v-for="v in priorityList" :key="v.dcode" :label="v.dname" :value="v.dcode" />
                            </el-select>
                            <!-- 选择影响范围 -->
                            <el-select
                              v-if="vo.attrdataDictionary == 'effectRange'"
                              v-model="vo.value"
                              placeholder="请选择影响范围"
                            >
                              <el-option v-for="v in effectRangeList" :key="v.dcode" :label="v.dname" :value="v.dcode" />
                            </el-select>
                            <!-- 选择紧急度 -->
                            <el-select
                              v-if="vo.attrdataDictionary == 'seriousness'"
                              v-model="vo.value"
                              placeholder="请选择紧急度"
                            >
                              <el-option v-for="v in seriousnessList" :key="v.dcode" :label="v.dname" :value="v.dcode" />
                            </el-select>
                          </template>
                        </div>
                      </div>
                    </div>
                  </div>
                  <div v-if="attrVals.length == 0" style="color: #999999">暂无拓展数据</div>
                </el-tab-pane>
                <el-tab-pane label="附件" name="two">
                  <el-upload ref="uploadRef" action="" :auto-upload="false" :show-file-list="false" :on-change="uploadChange">
                    <template #trigger>
                      <el-button type="primary" plain>添加附件</el-button>
                    </template>
                    <!-- <template #tip>
                    <div class="el-upload__tip">jpg/png files with a size less than 500kb</div>
                  </template> -->
                  </el-upload>
                  <el-table :data="enclosureList" border style="margin-top: 10px">
                    <el-table-column label="名称" prop="attachmentName"></el-table-column>
                    <el-table-column label="服务器路径" prop="url"></el-table-column>
                    <el-table-column label="操作" align="center" width="180">
                      <template #default="scope">
                        <el-button @click="delFile(scope.row)">删除</el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </el-tab-pane>
                <el-tab-pane label="关联配置项" name="three">
                  <div style="margin-bottom: 10px">
                    <el-button type="primary" @click="showSelectAssetMask">添加配置项</el-button>
                  </div>
                  <el-table border :data="assetList" max-height="400px">
                    <el-table-column label="固定资产编号" prop="cino"></el-table-column>
                    <el-table-column label="名称" prop="ciname"></el-table-column>
                    <el-table-column label="分类" prop="categoryName"></el-table-column>
                    <el-table-column label="状态" prop="status"></el-table-column>
                    <el-table-column label="操作" width="150" align="center">
                      <template #default="scope">
                        <el-button @click="delAsset(scope.row)">删除</el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </el-tab-pane>
                <el-tab-pane label="关联服务" name="four">
                  <div style="margin-bottom: 10px">
                    <el-button type="primary" @click="showSelectServesMask">添加服务</el-button>
                  </div>
                  <el-table border :data="serviceDirectoryList" max-height="400px">
                    <el-table-column type="index" label="序号" width="120" align="center"></el-table-column>
                    <el-table-column label="服务名称" prop="cname"></el-table-column>
                    <el-table-column label="操作" width="150" align="center">
                      <template #default="scope">
                        <el-button @click="delServe(scope.row)">删除</el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </el-tab-pane>
              </el-tabs>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </template>
    </el-drawer>
    <!-- 选择配置项（资产） -->
    <SelectAssetMask v-if="dialogVisible" ref="selectAssetMask" @change="assetChange"></SelectAssetMask>
    <!-- 选择服务 -->
    <SelectServesMask v-if="dialogVisible" ref="selectServesMask" @change="serveChange"></SelectServesMask>
  </div>
</template>

<script setup lang="ts" name="AddProblemMask">
import { ref, computed, reactive, watch, onMounted } from "vue";

import { ElMessage, ElMessageBox } from "element-plus";

import { requestAllOptions } from "@/stores/modules/event";
import { useUserStore } from "@/stores/modules/user";

import { findAllEventAttachment, attributeList, uploadAttr } from "@/api/modules/common";
import { getCategoryTree, saveProblem } from "@/api/modules/problem";

import WangEditor from "@/components/WangEditor/index.vue";
import SelectServesMask from "@/components/SelectServesMask/index.vue";
import SelectAssetMask from "@/components/SelectAssetMask/index.vue";

const allRequestOptions = requestAllOptions();
const userStore = useUserStore();

const props = defineProps({
  type: {
    type: String,
    default: ""
  }
});

interface OrgItem {
  orgNo: string;
  orgName: string;
}

// 所属客户列表
const orgList = computed(() => {
  let list = ref<OrgItem[]>(allRequestOptions.orgList || []);
  let companyNo = userStore.userInfo.companyNo;
  let hasItem = false;
  list.value.forEach((item: any) => {
    if (item.orgNo === companyNo) {
      hasItem = true;
    }
  });
  if (!hasItem) {
    list.value.push({
      orgName: userStore.userInfo.companyName,
      orgNo: userStore.userInfo.companyNo
    });
  }
  return list.value;
});

interface CateItem {
  id: string;
  cname: string;
  eavId: number;
}

// 问题分类列表
const cateList = ref<CateItem[]>([]);

interface UniversalItem {
  dcode: string;
  dname: string;
}

// 优先级列表
const priorityList = computed<UniversalItem[]>(() => {
  return allRequestOptions.priorityList;
});

// 影响列表
const effectRangeList = computed<UniversalItem[]>(() => {
  return allRequestOptions.effectRangeList;
});

// 紧急度列表
const seriousnessList = computed<UniversalItem[]>(() => {
  return allRequestOptions.seriousnessList;
});

onMounted(() => {
  getCategoryTree({
    types: "Problem",
    parentEventId: 0
  }).then((res: any) => {
    cateList.value = res.children.map(item => {
      return item.attr;
    });
  });
  if (
    orgList.value.length == 0 ||
    priorityList.value.length == 0 ||
    effectRangeList.value.length == 0 ||
    seriousnessList.value.length == 0
  ) {
    allRequestOptions.getAllOptions();
  }
});

const dialogVisible = ref(false);
const loading = ref(false);
const rules = reactive({
  etitle: [{ required: true, message: "请输入请求标题", trigger: "blur" }],
  companyNo: [{ required: true, message: "请选择所属客户", trigger: "change" }]
});
const form = reactive({
  etitle: "", // 问题标题
  edesc: "", // 问题描述
  companyNo: "", // 所属客户
  companyName: "",
  categoryNo: "", // 问题分类
  categoryName: "",
  statusCode: "", // 状态
  overdueTime: "", // 期望完成时间
  priorityNo: "", // 优先级
  effectRangeNo: "", // 影响范围
  seriousnessNo: "" // 紧急度
});

const tabName = ref("one");

// 拓展信息列表
const attrVals = ref<any>([]);

// 监听分类
watch(
  () => form.categoryNo,
  val => {
    attrVals.value = [];
    if (val) {
      cateList.value.forEach(item => {
        if (item.id == val) {
          form.categoryName = item.cname;
          if (item.eavId) {
            attributeList({
              eavNo: item.eavId
            }).then((res: any) => {
              let list = res || [];
              let arr = ref<any[]>([]);
              list.forEach(item => {
                item.value = "";
                if (arr.value.length == 0) {
                  arr.value.push({
                    attrGroupName: item.attrGroupName,
                    children: [item]
                  });
                } else {
                  let hasAttrGroupName = false;
                  arr.value.forEach(vo => {
                    if (vo.attrGroupName == item.attrGroupName) {
                      hasAttrGroupName = true;
                      vo.children.push(item);
                    }
                  });
                  if (!hasAttrGroupName) {
                    arr.value.push({
                      attrGroupName: item.attrGroupName,
                      children: [item]
                    });
                  }
                }
              });
              attrVals.value = arr.value;
            });
          }
        }
      });
    }
  }
);

import type { UploadProps } from "element-plus";
const enclosureList = ref<any[]>([]); // 附件列表
// 上传附件
const uploadChange: UploadProps["onChange"] = (uploadFile: any) => {
  loading.value = true;
  let params = new FormData();
  params.append("filedata", uploadFile.raw);
  uploadAttr("yuehaishuiwu_zhengshi", params)
    .then(res => {
      loading.value = false;
      enclosureList.value.push({
        attachmentName: uploadFile.name,
        url: res.msg,
        size: uploadFile.size
      });
    })
    .catch(() => {
      loading.value = false;
    });
};

// 删除附件
const delFile = (item: { url: any }) => {
  ElMessageBox.confirm("确定要删除该附件？", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(() => {
      let index = 0;
      enclosureList.value.forEach((vo, idx) => {
        if (vo.url === item.url) {
          index = idx;
        }
      });
      enclosureList.value[index].splice(index, 1);
    })
    .catch(() => {
      // cancel operation
    });
};

// 选择配置项
const selectAssetMask = ref();
const showSelectAssetMask = () => {
  selectAssetMask.value?.open();
};
const assetList = ref<any[]>([]);
const assetChange = list => {
  list.forEach(data => {
    console.log(data);
    let has_item = false;
    assetList.value.forEach(item => {
      if (item.ciId == data.ciId) {
        has_item = true;
      }
    });
    // ElMessage.warning("已选择该资产，无需重复选择");
    if (!has_item) {
      assetList.value.push(data);
    }
  });
};
const delAsset = item => {
  let index = 0;
  assetList.value.forEach((element, idx) => {
    if (element.ciId == item.ciId) {
      index = idx;
    }
  });
  assetList.value.splice(index, 1);
};

// 选择服务
const serviceDirectoryList = ref<any[]>([]);
const selectServesMask = ref();
const showSelectServesMask = () => {
  selectServesMask.value?.open();
};
// 选择服务
const serveChange = list => {
  serviceDirectoryList.value = list;
};
// 删除服务
const delServe = item => {
  let index = 0;
  serviceDirectoryList.value.forEach((element, idx) => {
    if (element.id == item.id) {
      index = idx;
    }
  });
  serviceDirectoryList.value.splice(index, 1);
};

// 定义 emit 事件
const emit = defineEmits<{
  change: [];
  add: [];
}>();

const addForm = ref();
const details = ref<any>({});
const submit = async () => {
  await addForm.value.validate((valid, fields) => {
    if (valid) {
      if (!form.edesc) {
        ElMessage.warning("请输入描述");
        return false;
      }
      // 拓展信息
      let attrValsData = ref<any>({});
      if (attrVals.value.length > 0) {
        attrVals.value.forEach(element => {
          element.children.forEach(item => {
            let key = "problemDTO.attrVals[" + item.attrName + "]";
            attrValsData.value[key] = item.value;
          });
        });
      }
      // 附件
      let attachmentStr = "";
      if (enclosureList.value.length > 0) {
        enclosureList.value.forEach(item => {
          attachmentStr += item.attachmentName + "==" + item.url + "==" + item.size + "-s-";
        });
      }
      // 关联的配置项
      let ciIds = ref<any[]>([]);
      assetList.value.forEach(item => {
        ciIds.value.push("problemDTO.ciIds=" + item.ciId);
      });
      // 关联的服务
      let serviceIds = ref<any[]>([]);
      serviceDirectoryList.value.forEach(item => {
        serviceIds.value.push("problemDTO.serviceDirectoryIds=" + item.id);
      });
      // 组装数据（关联的配置项+关联的服务）
      let ciIdsAndServiceDirectoryIds = "";
      if (ciIds.value.length > 0 && serviceIds.value.length > 0) {
        ciIdsAndServiceDirectoryIds = ciIds.value.join("&") + "&" + serviceIds.value.join("&");
      } else if (ciIds.value.length > 0) {
        ciIdsAndServiceDirectoryIds = ciIds.value.join("&");
      } else if (serviceIds.value.length > 0) {
        ciIdsAndServiceDirectoryIds = serviceIds.value.join("&");
      }
      if (props.type == "upgrade") {
        // 请求升级成问题
        saveProblem(ciIdsAndServiceDirectoryIds, {
          "problemDTO.createdByName": userStore.username,
          "problemDTO.piv.approvalNo": details.value.approvalNo,
          "problemDTO.piv.eventCode": details.value.eventCode,
          "problemDTO.piv.etitle": details.value.etitle,
          "problemDTO.piv.eno": details.value.eno,
          "problemDTO.companyNo": form.companyNo,
          "problemDTO.companyName": form.companyName,
          "problemDTO.etitle": form.etitle,
          "problemDTO.edesc": form.edesc,
          "problemDTO.categoryNo": form.categoryNo,
          "problemDTO.categoryName": form.categoryName,
          "problemDTO.overdueTime": form.overdueTime,
          "problemDTO.priorityNo": form.priorityNo,
          "problemDTO.effectRangeNo": form.effectRangeNo,
          "problemDTO.seriousnessNo": form.seriousnessNo,
          ...attrValsData, // 拓展信息
          "problemDTO.attachmentStr": attachmentStr // 附件
        })
          .then(() => {
            ElMessage.success("保存成功");
            dialogVisible.value = false;
            emit("add");
          })
          .catch(err => {
            ElMessage.error(err.msg || err.message || err.data || "提交失败");
          });
      } else if (details.value.eno) {
        // 编辑
        // todo
      } else {
        // 新增
        saveProblem(ciIdsAndServiceDirectoryIds, {
          "problemDTO.createdByName": userStore.username,
          "problemDTO.piv.approvalNo": "",
          "problemDTO.piv.eventCode": "",
          "problemDTO.piv.etitle": "",
          "problemDTO.piv.eno": "",
          "problemDTO.companyNo": form.companyNo,
          "problemDTO.companyName": form.companyName,
          "problemDTO.etitle": form.etitle,
          "problemDTO.edesc": form.edesc,
          "problemDTO.categoryNo": form.categoryNo,
          "problemDTO.categoryName": form.categoryName,
          "problemDTO.overdueTime": form.overdueTime,
          "problemDTO.priorityNo": form.priorityNo,
          "problemDTO.effectRangeNo": form.effectRangeNo,
          "problemDTO.seriousnessNo": form.seriousnessNo,
          ...attrValsData, // 拓展信息
          "problemDTO.attachmentStr": attachmentStr // 附件
        })
          .then(() => {
            ElMessage.success("保存成功");
            dialogVisible.value = false;
            emit("add");
          })
          .catch(err => {
            ElMessage.error(err.msg || err.message || err.data || "提交失败");
          });
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};

const open = (item: any) => {
  // 循环遍历清空表单
  for (const key in form) {
    form[key] = "";
  }
  dialogVisible.value = true;
  if (item.eno) {
    details.value = { ...item };
    form.etitle = item.etitle;
    form.edesc = item.edesc;
    form.companyNo = item.companyNo;
    form.companyName = item.companyName;
    if (props.type == "upgrade") {
      // 请求升级成问题
      findAllEventAttachment({
        "eventAttachmentDto.eno": item.eno,
        "eventAttachmentDto.eventType": "itsm.request"
      }).then((res: any) => {
        // 附件列表
        enclosureList.value = res || [];
      });
    } else {
      // 编辑
      // todo
    }
  }
  if (
    orgList.value.length == 0 ||
    priorityList.value.length == 0 ||
    effectRangeList.value.length == 0 ||
    seriousnessList.value.length == 0
  ) {
    allRequestOptions.getAllOptions();
  }
};

defineExpose({
  open
});
</script>
